//
//  PlatformInvitationViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-10-25.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "PlatformInvitationViewController.h"
#import "JSONRequest.h"
#import "JMFBase.h"
#import "ASImageView.h"
#import "pinyin.h"
#import "InvitationMessageViewController.h"
#import "Contact.h"
#import <AddressBook/AddressBook.h>

@interface PlatformInvitationViewController ()<JSONRequestDelegate>

@end

@implementation PlatformInvitationViewController
{
    NSMutableArray *_dataSource;
    NSMutableArray *_sectionForDataSource;          //按字母分组后的数据
    
    NSMutableArray *_localContacts;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        _localContacts = [NSMutableArray new];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.title = _L(@"vc_title_106");
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    //左侧导航按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    //右侧导航按钮：邀请
    UIButton *inviteButton = [Helper buttonWithStyle:ButtonStyleNavigationInvite];
    [inviteButton addTarget:self action:@selector(inviteButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:inviteButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    [self loadLocalContacts];
    
    [self obtainFriendsData];
//    
//    //显示一段表示此列表的内容的文字
//    UILabel *wordsLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 300.0f, 25.0f)];
//    wordsLabel.text = [NSString stringWithFormat:_L(@"tpl_50"), _L(@"vc_title_001")];
//    wordsLabel.font = _SYS_FONT_003;
//    self.tableView.tableHeaderView = wordsLabel;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    _dataSource = nil;
    _sectionForDataSource = nil;
}

#pragma mark - 私有方法

- (void)obtainFriendsData
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_FRIEND_REGISTER];
    request.delegate = self;
    request.hudOn = YES;
    request.hudTitle = _L(@"title_loading_01");
    [request asynchronous];
}

- (NSMutableArray *)sectionForFriends
{
    NSMutableArray* sections = [[NSMutableArray alloc] init];
    
    // 组装分区表初始默认数组
    // 循环将27个数组加入 分区数组(27个数组代表26个英文字母+1个＃号特殊字符)
    for (int i = 0; i < 27; i++) {
        [sections addObject:[NSMutableArray array]];
    }
    
    // 循环姓名数组
    for (NSMutableDictionary* person in _dataSource) {
        // 得到当前元素姓名
        NSString *contactsName = [person objectForKey:@"realName"];
        
        // 1、得到姓名0索引位置的字符
        // 2、调用pinyin类实例方法pinyinFirstLetter并传入字符，判断传入的字符是汉字还是英文，如果是汉字返回汉字所属的字母，不属于汉字返回传入字符
        // 3、将拼音方法传回的字符组装成字符串
        // 4、并转换成大写格式
        NSString *sectionPinYinLetter = nil;
        NSUInteger firstLetterLocation = NSNotFound;
        //长度检查，空名字不截取
        if (contactsName != nil && contactsName.length > 0) {
            sectionPinYinLetter = [[NSString stringWithFormat:@"%c",pinyinFirstLetter([contactsName characterAtIndex:0])] uppercaseString];
            firstLetterLocation = [ALPHA rangeOfString:[sectionPinYinLetter substringToIndex:1]].location;
        }
        
        // 1、截取sectionUgoName的第一个字符
        // 2、并判断此字符在26个英文字母+#号的位置，并赋值
        
        // 如果在26个之中的字母组成数组中有这个位置
        if (firstLetterLocation != NSNotFound) {
            // 找到ugo分区数组，在这个索引位置对应的数组，并加入同样属于索引i对应元素，及UgoContacts类的对象
            [[sections objectAtIndex:firstLetterLocation] addObject:person];
        }
        // 否则不在26个英文字母之中，用ALPHA数组最后一个特殊#号位置数组统一加入管理
        else {
            [[sections objectAtIndex:[ALPHA length] - 1] addObject:person];
        }
    }
    
    return sections;
}

/*!
 @abstract 初始化分区数据(组装分区数组、姓名数组、根据abc...z  26个字母对应26个分区+1个特殊分区＃号，对应字母分区放入对应姓名字母开头实体)
 */
- (void) sectionInitData
{
    // 查看通讯簿是否存在数据
    if ([_dataSource count] > 0) {
        // 清除以前分区数据
        _sectionForDataSource = nil;
        
        // 获取新分区数据
        _sectionForDataSource = [self sectionForFriends];
    }
}

//获取系统通讯录信息
- (void)loadLocalContacts
{
    ABAddressBookRef addressBookRef = nil;
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
    {
        addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
        //等待同意后向下执行
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error)
                                                 {
                                                     dispatch_semaphore_signal(sema);
                                                 });
        
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        dispatch_release(sema);
    }
    else
    {
        addressBookRef = ABAddressBookCreate();
    }
    
    CFArrayRef arrayRef = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
    NSArray* systemAddressBook = CFBridgingRelease(arrayRef);
    
    if (systemAddressBook.count <= 0) {
        [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_22")];
        return;
    }
    
    for (int i = 0; i < systemAddressBook.count; i++) {
        //转换一个联系人出来
        ABRecordRef recordRef = (__bridge ABRecordRef)[systemAddressBook objectAtIndex:i];//CFBridgingRetain([systemAddressBook objectAtIndex:i]);
        
        // 获取联系人记录首名并赋值
        NSString* firstName = CFBridgingRelease(ABRecordCopyValue(recordRef, kABPersonFirstNameProperty));
        // 获取联系人记录末名并赋值
        NSString* lastName = CFBridgingRelease(ABRecordCopyValue(recordRef, kABPersonLastNameProperty));
        
        NSString* fullName = [NSString stringWithFormat:@"%@ %@", (lastName ? lastName : @""), (firstName ? firstName : @"")];
        
        NSString *mobile;
        NSMutableArray *mobiles;
        ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(recordRef, kABPersonPhoneProperty);
        if (ABMultiValueGetCount(phoneMulti) != 0) {
            
            if (mobiles == nil) {
                mobiles = [[NSMutableArray alloc] init];
            }
            
            //将电话数组置为空，进行下一次遍历
            if (mobiles.count != 0) {
                [mobiles removeAllObjects];
            }
            
            for (int k = 0; k < ABMultiValueGetCount(phoneMulti); k++) {
                
                CFStringRef numberRef = ABMultiValueCopyValueAtIndex(phoneMulti, k);
                
                mobile = CFBridgingRelease(numberRef);
                
                //获得一个联系人的所有电话
                [mobiles addObject:[Helper cleanPhone:mobile]];
            }
        }
        
        CFRelease(phoneMulti);
        CFRelease(recordRef);
        
        [_localContacts addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:fullName, @"name", mobiles, @"mobiles", nil]];
        
    }

}

/**
 *  返回好友在系统通讯簿中的姓名
 *
 *  @return NSString类型 好友在系统通讯簿中的姓名
 */
- (NSString *)realNameInSystemContactWithMobile:(NSString *)mobile
{
    
    if (_localContacts.count == 0) {
        return @"";
    }
    
    for (NSDictionary *dict in _localContacts) {
        
        NSArray *mobiles = [dict objectForKey:@"mobiles"];
        
        if ([mobiles count] != 0 && [mobiles indexOfObject:mobile] != NSNotFound) {

            return [NSString stringWithFormat:@"（%@）",[dict objectForKey:@"name"]];
        }
    }
    
    return @"";
}

#pragma mark - 事件
/*!
 @abstract 返回按钮点击事件
 */
- (void)backButtonEvent
{
    BOOL isFinished = YES;          //判断此次邀请操作是否完结，如果未完结，用户点击了返回，就和往常一样提示用户
    
    for (NSMutableDictionary *dict in _dataSource) {
        if ([[dict objectForKey:@"isSelected"] integerValue] == 1) {
            isFinished = NO;
        }
    }
    
    if (!isFinished) {
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_86") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        [alertView show];
    }
    else {
        [self.navigationController popViewControllerAnimated:true];
    }
}

- (void)inviteButtonEvent:(id)sender
{
    
    //点击邀请后，就获取那些被选中的好友，通过字段isSelected来判断，==1表示被用户选中
    NSMutableArray *contacts = [NSMutableArray new];
    
    for (NSMutableDictionary *dict in _dataSource) {

        if ([[dict objectForKey:@"isSelected"] integerValue] == 1) {
            
            Contact *contact = [Contact new];
            contact.name = [dict objectForKey:@"realName"];
            contact.mobile = [Helper decryptCiphertext:[dict objectForKey:@"mobile"]];
            
            contact.status = 1;                                 //都已注册过
            
            [contacts addObject:contact];
        }
    }
    
    //如果用户未选择好友，就不让它到发送验证信息页面
    if (contacts.count == 0) {
        [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_131")];
        return;
    }
    
    //在此加入进入到下级页面的代码
    InvitationMessageViewController* picker = [[InvitationMessageViewController alloc] init];
    picker.contactsToInvite = contacts;
    [self.navigationController pushViewController:picker animated:true];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[_sectionForDataSource objectAtIndex:section] count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 27;
}

// 分区标题头(分区栏最上面出现对应abc...)
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    // 存在本地联系人数据
    if (_dataSource.count > 0) {
        // 如果当前分区对应数组中没有数据
        if ([[_sectionForDataSource objectAtIndex:section] count] > 0) {
            // 返回26个英文字母+1个＃号特殊字符中,指定分区索引的一个字母
            // 截取字符串解析  (26个英文字母+1个＃号特殊字符,指定分区索引开始截取 ＝ 保留右边数据) (右边数据只截取到索引1处 ＝ 保留左边数据)
            NSString *headerTitleString = [NSString stringWithFormat:@"%@", [[ALPHA substringFromIndex:section] substringToIndex:1]];
            
            return headerTitleString;
        }
        else {
            return nil;
        }
    }
    
    return nil;
}

// 右侧A-Z
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    // 存在本地地址薄数据
    if (_sectionForDataSource.count > 0) {
        NSMutableArray *indices = [NSMutableArray array];
        // 26个英文字母+1个＃号特殊字符
        for (int i = 0; i < 27; i++) {
            // 将首字母加入数组
            // 截取字符串解析  (26个英文字母中,指定分区索引开始截取 ＝ 保留右边数据) (右边数据只截取到索引1处 ＝ 保留左边数据)
            [indices addObject:[[ALPHA substringFromIndex:i] substringToIndex:1]];
        }
        return indices;
    }
    
    // 查询表
	return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        ASImageView* imageView = [[ASImageView alloc] initWithFrame:CGRectMake(8, 9, 35, 35)];
        imageView.tag = 100;
        
        [cell.contentView addSubview:imageView];
        
        
        UILabel* nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(X_AND_WIDTH(imageView.frame)+5.0f, 18, 220, 20)];
        nameLabel.font = _SYS_FONT_004;
        nameLabel.tag = 101;

        [cell.contentView addSubview:nameLabel];
        
        
        UIImageView* checkImageView = [[UIImageView alloc] initWithFrame:CGRectMake(270, 13, 18, 18)];
        cell.accessoryView = checkImageView;
    }
    
    NSDictionary* friend = [[_sectionForDataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    [(ASImageView *)[cell.contentView viewWithTag:100] setImageURL:[NSURL URLWithString:[friend objectForKey:@"previewAvatar"]] andSourceImageURL:nil forStyle:PictureStyleCircleMemberAvart];
    
    //通过手机号码匹配出好友在系统通讯簿中的名字
    NSString *realNameInContacts = [self realNameInSystemContactWithMobile:[Helper decryptCiphertext:[friend objectForKey:@"mobile"]]];
    
    [((UILabel *)[cell.contentView viewWithTag:101]) setText:[NSString stringWithFormat:@"%@%@",[friend objectForKey:@"realName"],realNameInContacts]];
    
    NSInteger isSelected = [[friend objectForKey:@"isSelected"] integerValue];
    //勾选
    if (isSelected == 1) {
        
        ((UIImageView *)cell.accessoryView).image = [UIImage imageNamed:@"com_icon_011"];
    }
    //取消
    else {
        
        ((UIImageView *)cell.accessoryView).image = [UIImage imageNamed:@"com_icon_010"];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0f;
}

#pragma mark - Table view Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    NSMutableDictionary *friend = [[_sectionForDataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    NSMutableDictionary *originalDataForFriend = [_dataSource objectAtIndex:[_dataSource indexOfObject:friend]];
    
    NSInteger isSelected = [[friend objectForKey:@"isSelected"] integerValue];
    
    //勾选或取消操作
    //勾选时同时要更新原数据和分组后的数据的isSelected（好友是否被选中）字段
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    //勾选
    if (isSelected == 0) {
        
        [friend setObject:@(1) forKey:@"isSelected"];
        ((UIImageView *)cell.accessoryView).image = [UIImage imageNamed:@"com_icon_011"];
        
        [originalDataForFriend setObject:@(1) forKey:@"isSelected"];
    }
    //取消
    else {
        
        [friend setObject:@(0) forKey:@"isSelected"];
        ((UIImageView *)cell.accessoryView).image = [UIImage imageNamed:@"com_icon_010"];
        
        [originalDataForFriend setObject:@(0) forKey:@"isSelected"];
    }
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {

        //向数据源中添加一个用标记好友是否被标记的字段，由于得到的数据都是不可变对象，所以要转成可变对象
        
        if ([(NSArray *)jmf.data count] != 0) {
            
            _dataSource = [NSMutableArray new];
            
            for (NSDictionary *dict in (NSArray *)jmf.data) {
                
                NSMutableDictionary *friend = [NSMutableDictionary new];
                [friend addEntriesFromDictionary:dict];
                
                [friend setObject:@(0) forKey:@"isSelected"];
                
                [_dataSource addObject:friend];
            }
            
            //分组操作
            [self sectionInitData];
            [self.tableView reloadData];
        }
        else {
            
            self.navigationItem.rightBarButtonItem = nil;
        }
        
        
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - UIAlertView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        
        [self.navigationController popViewControllerAnimated:true];
    }
}
@end
